#!groovy
@Library('devops-sharelibrary@release-v2') _


properties([gitLabConnection(''), [$class: 'RebuildSettings', autoRebuild: false, rebuildDisabled: false], parameters([[$class: 'ChoiceParameter', choiceType: 'PT_SINGLE_SELECT', description: '请选择部门', filterLength: 1, filterable: true, name: 'Department', randomName: 'choice-parameter-623606125965381', script: [$class: 'GroovyScript', fallbackScript: [classpath: [], sandbox: false, script: ''], script: [classpath: [], sandbox: false, script: '''import groovy.json.JsonSlurper
try {
    List<String> artifacts = new ArrayList<String>()
    def artifactsUrl = "https://ultron.devops.net/api/v1/argocd/projects"          
    def artifactsObjectRaw = ["curl", "-s", "-k", "--url", "${artifactsUrl}"].execute().text
    def jsonSlurper = new JsonSlurper()
    def artifactsJsonObject = jsonSlurper.parseText(artifactsObjectRaw)
    def dataArray = artifactsJsonObject.data
    for(item in dataArray){
        artifacts.add(item.name)
    } 
    return artifacts
} catch (Exception e) {
    print "There was a problem fetching the artifacts"
}''']]], [$class: 'CascadeChoiceParameter', choiceType: 'PT_SINGLE_SELECT', description: '请选择kubernetes集群', filterLength: 1, filterable: true, name: 'Cluster', randomName: 'choice-parameter-623606127552285', referencedParameters: 'Department', script: [$class: 'GroovyScript', fallbackScript: [classpath: [], sandbox: false, script: ''], script: [classpath: [], sandbox: false, script: '''import groovy.json.JsonSlurper

try {
    List<String> artifacts = new ArrayList<String>()
    def artifactsUrl = "https://ultron.devops.net/api/v1/argocd/projects"
    def artifactsObjectRaw = ["curl", "-s", "-k", "--url", "${artifactsUrl}"].execute().text
    def jsonSlurper = new JsonSlurper()
    def artifactsJsonObject = jsonSlurper.parseText(artifactsObjectRaw)
    def dataArray = artifactsJsonObject.data
    for(item in dataArray){
        if (Department.equals(item.name)) {
            item.destinations.keySet().each{it -> artifacts +=it }
            return artifacts
        }
    }
} catch (Exception e) {
    print e
    print "There was a problem fetching the artifacts"
}''']]], [$class: 'CascadeChoiceParameter', choiceType: 'PT_SINGLE_SELECT', description: '', filterLength: 1, filterable: true, name: 'FromEnv', randomName: 'choice-parameter-8032909055009506', referencedParameters: 'Department,Cluster', script: [$class: 'GroovyScript', fallbackScript: [classpath: [], sandbox: false, script: ''], script: [classpath: [], sandbox: false, script: '''import groovy.json.JsonSlurper
try {
    List<String> artifacts = new ArrayList<String>()
    def artifactsUrl = "https://ultron.devops.net/api/v1/argocd/projects"
    def artifactsObjectRaw = ["curl", "-s", "-k", "--url", "${artifactsUrl}"].execute().text
    def jsonSlurper = new JsonSlurper()
    def artifactsJsonObject = jsonSlurper.parseText(artifactsObjectRaw)
    def dataArray = artifactsJsonObject.data
    for(item in dataArray){
        // artifacts.add(item.destinations.keySet().each())
        if (Department.equals(item.name)) {
            for ( key in item.destinations.keySet()) {
                if (Cluster.equals(key)) {
                    item.destinations.get(Cluster).each{it -> artifacts +=it }
                    return artifacts
                    break;
                }
            }
        }
    }
    // return (artifacts.unique())
} catch (Exception e) {
    print e
    print "There was a problem fetching the artifacts"
}''']]], [$class: 'CascadeChoiceParameter', choiceType: 'PT_SINGLE_SELECT', description: '', filterLength: 1, filterable: true, name: 'ToEnv', randomName: 'choice-parameter-8032909056623075', referencedParameters: 'Department,Cluster', script: [$class: 'GroovyScript', fallbackScript: [classpath: [], sandbox: false, script: ''], script: [classpath: [], sandbox: false, script: '''import groovy.json.JsonSlurper
try {
    List<String> artifacts = new ArrayList<String>()
    def artifactsUrl = "https://ultron.devops.net/api/v1/argocd/projects" 
    def artifactsObjectRaw = ["curl", "-s", "-k", "--url", "${artifactsUrl}"].execute().text
    def jsonSlurper = new JsonSlurper()
    def artifactsJsonObject = jsonSlurper.parseText(artifactsObjectRaw)
    def dataArray = artifactsJsonObject.data
    for(item in dataArray){
        // artifacts.add(item.destinations.keySet().each())
        if (Department.equals(item.name)) {
            for ( key in item.destinations.keySet()) {
                if (Cluster.equals(key)) {
                    item.destinations.get(Cluster).each{it -> artifacts +=it }
                    return artifacts
                    break;
                }
            }
        }
    }
    // return (artifacts.unique())
} catch (Exception e) {
    print e
    print "There was a problem fetching the artifacts"
}''']]], [$class: 'CascadeChoiceParameter', choiceType: 'PT_MULTI_SELECT', description: '', filterLength: 1, filterable: false, name: 'ApplicationSelect', randomName: 'choice-parameter-9234868051950429', referencedParameters: 'Department,FromEnv', script: [$class: 'GroovyScript', fallbackScript: [classpath: [], sandbox: false, script: ''], script: [classpath: [], sandbox: false, script: '''import groovy.json.JsonSlurper
try {
    List<String> artifacts = new ArrayList<String>()
    def artifactsUrl = "http://wefocus-api.devops.net/api/wefocus/v1/get_department_env_parameters_info?department=${Department}&env=${FromEnv}"          
    def artifactsObjectRaw = ["curl", "-s", "-k", "--url", "${artifactsUrl}"].execute().text
    def jsonSlurper = new JsonSlurper()
    def artifactsJsonObject = jsonSlurper.parseText(artifactsObjectRaw)
    def dataArray = artifactsJsonObject.data
    for(item in dataArray){
        artifacts.add(item.applicationName)
    }
    artifacts.add(0,'all')
    return artifacts
} catch (Exception e) {
    print "There was a problem fetching the artifacts"
}''']]]])])

def HelmGitAddr
def HelmGitGroup
def HelmGitProj
def jobParameters = getParameters.getAllEnvParameters("${params.Department}","${FromEnv}")
def paramsMap = readJSON text: jobParameters
def allApps = getParameters.getAllEnvAPP("${params.Department}","${FromEnv}")

def appList

if ( "${params.ApplicationSelect}" == 'all' ) {
    appList = allApps
} else {
    appList = "${params.ApplicationSelect}".split(',')
}

appList.each { app ->
    println app
}
node('cicd-test') {
    if ("${FromEnv}" == "${ToEnv }") {
        currentBuild.result = 'ABORTED'
        error('You Must not copy job in the same environment')
    }
    appList.each { app ->
        paramsMap.each { parameters ->
            if (parameters["applicationName"] == app ) {
                stage("Print Local Messages") {
                        println parameters
                }
                stage('Prepare Envs') {
                    sh "echo 'reset and define some variables......'"
                    (Kx,Ky,HelmGitAddr,HelmGitGroup,HelmGitProj) = "${parameters.sourceRepo}".split('/')
                    sh "echo 'reset and define some variables......'"
                    env.GitGroup = "${parameters.projectRepo}".split(':|/')[1]
                    // 设置项目模块和编译时的模块路径
                    env.JenkinsFolder = "${parameters.department}-${env.GitGroup}-${params.ToEnv}"
                    env.HelmChartValueName = "${parameters.department}-${parameters.clusterCode}-${params.ToEnv}-${parameters.serviceName}"
                    // argo application 名称
                    env.ApplicationName = "${parameters.department}-${parameters.clusterCode}-${params.ToEnv}-${parameters.serviceName}"
                    env.K8sNamespace = "${parameters.department}-${params.ToEnv}"
                    env.JenkinsJobName = "${env.JenkinsFolder}/${parameters.department}-${parameters.clusterCode}-${parameters.projectType}-${params.ToEnv}-${parameters.serviceName}"
                    env.HealthCheck = true
                    echo "${env.JenkinsJobName}"
                }
                stage("Store Parameters ") {
                    storeParameters.jenkinsInit("${parameters.department}","${parameters.cluster}","${parameters.clusterCode}","${params.ToEnv}","${parameters.sourceRepo}",
                                    "${parameters.apiServer}","${parameters.projectType}","${parameters.compiler_version}","${parameters.projectRepo}","${parameters.module}",
                                    "${parameters.serviceName}","${parameters.packageName}","${parameters.port}","${parameters.jvm}","${parameters.healthCheckUrl}",
                                    "${parameters.ingress}","${parameters.ingressInternalType}","${parameters.ingressInternalHosts}","${parameters.ingressPublicType}","${parameters.ingressPublicHosts}",
                                    "${parameters.k8sService}","${parameters.k8sServiceName}","${parameters.affinity}","${parameters.dedicated}","${parameters.replicaset}",
                                    "${parameters.k8sCpuRequest}","${parameters.k8sMemoryRequest}","${parameters.k8sCpuLimit}","${parameters.k8sMemoryLimit}","${parameters.apollo}",
                                    "${parameters.apolloMetaServer}","${parameters.apolloEnv}","${parameters.apolloIDC}","${parameters.harborAddress}","${parameters.argoAddress}",
                                    "${env.JenkinsFolder}","${env.JenkinsJobName}","${env.HelmChartValueName}","${env.ApplicationName}","${env.K8sNamespace}","${parameters.goRootDir}","${env.HealthCheck}",)
                }
                stage('Create Jenkins Project View') {
                    jenkinsJobDsl.createView("${parameters.department}")
                }
                // create folder for environment
                stage('Create Jenkins Project Folder') {
                    jenkinsJobDsl.createFolder("estore-histore-test02")
                }
                // create a job for this project
                stage('Create Jenkins Pipeline Job') {
                    jenkinsJobDsl.createJob("${env.JenkinsJobName}")
                }
                stage('Create Helm Chart Value') {
                    dir("helm-chart") {
                        git([url: "git@${HelmGitAddr}:${HelmGitGroup}/${HelmGitProj}", branch: 'master', credentialsId: 'devopsGit'])
                        def healthCheck = true
                        echo "${parameters.projectType}"
                        helmValue("${parameters.department}","${params.ToEnv}","${parameters.projectType}","${parameters.harborAddress}","${parameters.module}","${parameters.port}","${parameters.apollo}","${parameters.apolloEnv}","${parameters.apolloMetaServer}","${parameters.ingress}","${healthCheck}","${parameters.healthCheckUrl}","${parameters.jvm}","${env.HelmChartValueName}","${parameters.affinity}","${parameters.dedicated}","${parameters.k8sService}","${parameters.k8sServiceName}","${parameters.k8sCpuLimit}","${parameters.k8sMemoryLimit}","${parameters.k8sCpuRequest}","${parameters.k8sMemoryRequest}","${parameters.ingressInternalType }","${parameters.ingressPublicType}","${parameters.ingressInternalHosts}","${parameters.ingressPublicHosts}","${parameters.apolloIDC}","${parameters.serviceName}")
                    }
                }
                stage('Push New Helm Chart Config') {
                    dir("helm-chart") {
                            try{
                                sshagent(['devopsGit']) {
                                    sh """
                                        git add .
                                        git commit -m 'add ${env.HelmChartValueName} values file'
                                        git push --set-upstream origin master
                                        git push -u origin master
                                    """
                                }
                            } catch (Exception e1) {
                                println("nothing to commit")
                            }
                    }
                }
                stage("Create ArgoCD application") {
                    createArgoApp("${parameters.department}","${parameters.projectType}","${parameters.argoAddress}","${env.ApplicationName}","${env.HelmChartValueName}","${parameters.apiServer}","${env.K8sNamespace}","${parameters.sourceRepo}")
                }
            }
        }
    }
}